package com.ganzalang.gmall.learning.netty.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @description: 从文件读取数据
 * @author: Ganzalang
 * @Date 2021/7/12 21:34
 */
@Slf4j
public class NIOFileChannel02 {

    public static void main(String[] args) throws IOException {
        File file = new File("D:\\file01.txt");
        // 创建文件的输入流
        FileInputStream fileInputStream = new FileInputStream(file);
        // 通过FileInputStream获取对应的FileChannel，其实现是FileChannelImpl
        FileChannel fileChannel = fileInputStream.getChannel();

        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
        // 将通道的数据读入到Buffer
        fileChannel.read(byteBuffer);

        // array()方法返回一个字节数组，将缓冲区的字节数据转成String
        log.info("byteBuffer's content: {}", new String(byteBuffer.array()));
        fileInputStream.close();
    }
}
